package cn.eva.service.Impl.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.eva.common.ResultJosn;
import cn.eva.dao.SysMenuMapper;
import cn.eva.dao.SysRoleMenuMapper;
import cn.eva.entity.SysMenu;
import cn.eva.example.SysMenuExample;
import cn.eva.example.SysMenuExample.Criteria;
import cn.eva.example.SysRoleMenuExample;
import cn.eva.service.admin.SysMenuService;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    /**
     * 增加菜单
     */
    @Override
    @Transactional
    public ResultJosn add(SysMenu menu) {
        menuMapper.insert(menu);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), null);
    }

    /**
     * 删除菜单
     */
    @Override
    @Transactional
    public ResultJosn delete(Long id) {
        // 删除角色-权限表
        this.deleteRoleMenu(id);
        // 删除子菜单
        this.deleteChildMenu(id);
        // 删除自己
        menuMapper.deleteByPrimaryKey(id);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), null);
    }

    /**
     * 更新菜单
     */
    @Override
    @Transactional
    public ResultJosn update(SysMenu menu) {
        if (null == menu.getId()) {
            throw new IllegalArgumentException("id错误");
        }
        menuMapper.updateByPrimaryKeySelective(menu);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), menu);
    }

    /**
     * 查询全部
     */
    @Override
    public ResultJosn select(SysMenu menu) {
        SysMenuExample example = new SysMenuExample();
        Criteria criteria = example.createCriteria();
        example.setOrderByClause("sort ASC");
        if (null != menu.getId()) {
            criteria.andIdEqualTo(menu.getId());
        } else if (null != menu.getType()) {
            criteria.andTypeEqualTo(menu.getType());
        }
        List<SysMenu> list = menuMapper.selectByExample(example);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), list);
    }

    /**
     * 删除角色-权限表
     * 
     * @param id
     */
    public void deleteRoleMenu(Long id) {
        SysRoleMenuExample example = new SysRoleMenuExample();
        example.createCriteria().andMenuIdEqualTo(id);
        roleMenuMapper.deleteByExample(example);
    }

    /**
     * 删除子菜单
     * 
     * @param pid
     */
    public void deleteChildMenu(Long pid) {
        SysMenuExample example = new SysMenuExample();
        example.createCriteria().andParentIdEqualTo(pid);
        menuMapper.deleteByExample(example);
    }

}
